﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.Bing.Service;

namespace Microsoft.Bing
{
    /// <summary>
    /// A default implementation of <see cref="ISearchEngine"/> which uses Microsoft Bing to provide search results.
    /// </summary>
    public class SearchEngine : ISearchEngine
    {
        /// <summary>
        /// Event which fires when a search completes.
        /// </summary>
        public event EventHandler<SearchResponseEventArgs> SearchCompleted;

        /// <summary>
        /// Event which fires when an error occurs when executing a search
        /// </summary>
        public event EventHandler<ErrorEventArgs> Error;

        /// <summary>
        /// Instantiates a <see cref="SearchEngine"/> instance.
        /// </summary>
        public SearchEngine()
        {

        }

        private const string SOAP_SERVICE_URL = "http://api.search.live.net:80/soap.asmx";

        private LiveSearchPortTypeClient    _Client = null;
        private DateTime                    _QueryStart;
        private DateTime                    _QueryEnd;
        private string                      _ServiceUrl = SOAP_SERVICE_URL;

        /// <summary>
        /// Gete/Sets the Service Url endpoint for the Microsoft Bing search (SOAP) web service
        /// <remarks>NOTE: This Url must be set before accessing the <see cref="Client"/> property and also before executing the <see cref="BeginSearch"/> method.</remarks>
        /// </summary>
        public string ServiceUrl
        {
            get { return _ServiceUrl; }
            set { _ServiceUrl = value; }
        }

        /// <summary>
        /// Gets the Microsoft Bing SOAP Client
        /// </summary>
        protected LiveSearchPortTypeClient Client
        {
            get
            {
                if (_Client == null)
                {
                    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
                    binding.MaxBufferSize = 2147483647;
                    binding.MaxReceivedMessageSize = 2147483647;
                    
                    EndpointAddress address = new EndpointAddress(_ServiceUrl);
                    _Client = new LiveSearchPortTypeClient(binding, address);
                    _Client.SearchCompleted += new EventHandler<SearchCompletedEventArgs>(OnHandleSearchCompleted);
                }

                return _Client;
            }
        }

        void OnHandleSearchCompleted(object sender, SearchCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                _QueryEnd = DateTime.Now;
                if (this.SearchCompleted != null) this.SearchCompleted(this, new SearchResponseEventArgs(e.Result));
            }
            else
            {
                OnError(e.Error, e.Cancelled);     
            }
        }

        void OnError(Exception ex, bool cancelled)
        {
            if (this.Error != null) this.Error(this, new ErrorEventArgs(ex, cancelled, this.Client.State));
        }

        #region ISearchEngine Members

        /// <summary>
        /// Gets a <see cref="System.TimeSpan"/> value which defines the amount of time consumed by the last search call
        /// </summary>
        public TimeSpan QueryTimeElapsed
        {
            get { return _QueryEnd - _QueryStart; }
        }

        /// <summary>
        /// Begins an asynchronous <see cref="SearchRequest"/> against the Microsoft Bind Search SOAP service
        /// </summary>
        /// <param name="search"></param>
        public void BeginSearch(SearchRequest search)
        {
            _QueryStart = DateTime.Now;
            this.Client.SearchAsync(search);
        }

        #endregion
    }
}
